import requests
import json
from datetime import datetime
import queue
import time
# from loggers import *
import logging
import threading

"""
流程：
机器检测完成为OK后上传条码和检测结果（hefei_message_update）返回值为1

需根据工位配置工作中心代码,产线代码,A码

软件启动时同时启动class http_server_mes用于获取token

上传过程中会自动保存日志在目录log下

url目前均为测试环境实际使用预计将更改

剩下参数根据客户需求更改
"""


def utc_time():
    gmt_format = '%a,%d %b %Y %H:%M:%S GMT+0800'
    utctime = datetime.utcnow().strftime(gmt_format)
    return utctime


def mes_token_get(ss):
    while True:
        url = "https://mesapi.midea.com/api/auth/SignIn"
        # url = "http://mesAPI.midea.com:80/api/Auth/SignIn"
        # url = 'http://127.0.0.1:5000/api'   #测试用
        payload = json.dumps({
            "user": "wangjl94",
            "pwd": "wangjl.92"
        })
        headers = {
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response.text)
        data = data['Data']['Token']
        # Tokentype = data['Data']['Token']
        hefei_token = 'Bearer ' + data
        ss.zz = hefei_token
        # print(data)
        time.sleep(900)
    # return 0


def time_now():
    date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return date_now


class MesServers:
    def __init__(self) -> None:
        self.zz = None
        self.si = queue.Queue()
        self.si.put(0)
        self.thread_work = None
        self.client_sockets = []
        self.thread_working = False
        self.start()

    def __del__(self):
        self.stop()

    def start(self):
        if self.thread_work is None:
            self.thread_working = True
            # mes_token_get(self)
            self.thread_work = threading.Thread(target=mes_token_get, args=(self,))
            self.thread_work.start()

    def hefei_message_update(self, pro, end):
        # pro为条码,end为检测结果0为OK，1为NG
        stepname = '弧面贴标'
        if end == 0:
            result = "PASS"
            totalErrCode = ""
            value = 1
        else:
            result = "FAIL"
            totalErrCode = "DefaultCode"
            value = 0
        midea_token = self.zz
        url = "https://mesapi.midea.com/API/DeviceGeneralTestApi/Test"
        # url = "http://mesAPI.midea.com:80/api/DeviceGeneralTestApiNew/Test"
        payload = json.dumps(
            {
                "INV_ORG_ID": "200808",
                "BARCODE": pro,
                "DATETIME_ACQUISITION": time_now(),
                "DEVICE_CODE": "A0401010003170561",  # 设备A码
                "totalSteps": "1",
                "TEST_STATUS": result,
                "detectionLine": "PZW1XT0002",  # 产线代码
                "WORKCENTER_CODE": "PZW1XT0002-HMBTJC",  # 工作中心
                "user": "AI_CHECK",
                "totalErrCode": totalErrCode,
                "detail": [
                    {
                        "stepNum": "1",
                        "stepName": stepname,
                        "stepResult": result,
                        "Args": [
                            {
                                "comment": stepname,
                                "value": value,
                                "result": result,
                                "test_conditions": ""
                            }
                        ]
                    }
                ]
            }
        )

        headers = {
            'Authorization': midea_token,
            'Content-Type': 'application/json'
        }
        datass = f"message_update{pro}"
        logging.info(datass)
        # log.info(datass)

        try:
            response = requests.request("POST", url, headers=headers, data=payload)
            data = json.loads(response.text)
            print(data)
        except Exception as e:
            datass = f"message_update{pro, e}"
            logging.error(datass)
            # log.info(datass)

        # print(data)
        return 1

    def stop(self):
        if self.thread_work is not None:
            self.thread_working = False
            self.thread_work.join()
            self.thread_work = None
        self.si.put(-1)

    def close(self):
        self.stop()

    def close_s(self, s):
        print('close_s:', s)
        self.close()

        return 0


if __name__ == "__main__":
    print(time_now())
    # mes_token_get()
    # http = http_server()
    # # time.sleep(5)
    # http.message_check('12345456')
